package capimServer;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * Intermediate class that check login 
 * @author danielm pessoafpc
 *
 */
public class LoginClass {
	/**
	 * Read the message and read the username and password
	 * @param message login message
	 * @param inetAddress ip address from the sender
	 */
	void checkMessage(String message, InetAddress inetAddress){
		StringBuffer userName 		= new StringBuffer();
		StringBuffer password 		= new StringBuffer();
		System.out.println("Message to unpack: "+message);
		char in;
		int count = 1;
		
		for(int i=0; i < message.length(); i++){
			in = message.charAt(i);
			switch(count){
			case 1:
				if (in == ':') count++;
				break;
				
			case 2:
				if (in == ':') count++;
				break;
				
			case 3:
				if (in == ':') count++;
				else userName.append(in);
				break;
				
			case 4:
				if (in == ':') count++;
				else password.append(in);
				break;
				
			default:
				break;
			
			}
			
		}
		
		// Check with the DB
		if(DB.checkUser(userName.toString(), password.toString())){
			System.out.println("Password OK!");
			try {
				// Send the response to the client
			CapimServer.postOffice.sendMessage(inetAddress, "131");
			} catch (NullPointerException e){
				e.printStackTrace();
			}
		} else {
			System.out.println("Invalid Password!");
			// Send the response to the client
			CapimServer.postOffice.sendMessage(inetAddress, "130");
		}
	}
}
